package com.fuluwa.infra.web;

import java.util.Map;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fuluwa.infra.exception.FlwRuntimeException;

public abstract class AbstractDomainController {

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	protected Result getSuccessResult(Object data) {
		Result successResult = Result.getSuccessResult();
		successResult.setData(data);
		return successResult;
	}

	protected Result getSuccessResult() {
		return Result.getSuccessResult();
	}

	protected Result getFailResult(String failMsg) {
		return Result.getFailResult(failMsg);
	}

	protected <T> T populate(Map<?, ?> map, T t) {
		try {
			BeanUtilsBean beanUtilsBean = new BeanUtilsBean(new ConvertUtilsBean() {
				@Override
				public Object convert(String value, Class clazz) {
					if (clazz.isEnum()) {
						return Enum.valueOf(clazz, value);
					} else {
						return super.convert(value, clazz);
					}
				}
			});
			beanUtilsBean.populate(t, map);
		} catch (Exception e1) {
			throw new FlwRuntimeException("populate failed:" + e1.getMessage(), e1);
		}
		return t;
	}
}
